'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Save, Eye, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label'
import { knowledgeAPI, categoriesAPI, tagsAPI } from '@/lib/api'
import { toast } from 'sonner'

interface Category {
  id: string
  name: string
}

interface Tag {
  id: string
  name: string
}

export default function CreateArticle() {
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isPreview, setIsPreview] = useState(false)
  
  // 表单数据
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    content: '',
    categoryId: '',
    tagIds: [] as string[],
    status: 'DRAFT' as 'DRAFT' | 'PUBLISHED',
    featured: false
  })

  // 分类和标签数据
  const [categories, setCategories] = useState<Category[]>([])
  const [tags, setTags] = useState<Tag[]>([])
  const [isLoadingData, setIsLoadingData] = useState(true)

  // 加载分类和标签数据
  useEffect(() => {
    const loadData = async () => {
      try {
        setIsLoadingData(true)
        const [categoriesRes, tagsRes] = await Promise.all([
          categoriesAPI.getCategories(),
          tagsAPI.getAllTags()
        ])
        setCategories(categoriesRes || [])
        setTags(tagsRes || [])
      } catch (error: any) {
        console.error('Failed to load data:', error)
        toast.error('加载分类和标签数据失败')
      } finally {
        setIsLoadingData(false)
      }
    }
    loadData()
  }, [])

  // 处理表单输入
  const handleInputChange = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 处理标签选择
  const handleTagToggle = (tagId: string) => {
    setFormData(prev => ({
      ...prev,
      tagIds: prev.tagIds.includes(tagId)
        ? prev.tagIds.filter(id => id !== tagId)
        : [...prev.tagIds, tagId]
    }))
  }

  // 保存文章
  const handleSave = async (status: 'DRAFT' | 'PUBLISHED') => {
    if (!formData.title.trim()) {
      toast.error('请输入文章标题')
      return
    }

    if (!formData.content.trim()) {
      toast.error('请输入文章内容')
      return
    }

    try {
      setIsSubmitting(true)
      
      const articleData = {
        ...formData,
        status
      }

      const result = await knowledgeAPI.createKnowledgeBase(articleData)
      
      toast.success(status === 'DRAFT' ? '草稿保存成功' : '文章发布成功')
      
      // 跳转到文章列表或编辑页面
      router.push('/knowledge')
    } catch (error: any) {
      console.error('Failed to save article:', error)
      toast.error(error.message || '保存文章失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 预览内容
  const togglePreview = () => {
    setIsPreview(!isPreview)
  }

  if (isLoadingData) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin" />
          <span>加载数据中...</span>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.back()}
          >
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-2xl font-bold">创建文章</h1>
            <p className="text-muted-foreground">创建新的知识库文章</p>
          </div>
        </div>
        
        <div className="flex space-x-2">
          <Button
            variant="outline"
            onClick={togglePreview}
            disabled={isSubmitting}
          >
            <Eye className="h-4 w-4 mr-2" />
            {isPreview ? '编辑' : '预览'}
          </Button>
          <Button
            variant="outline"
            onClick={() => handleSave('DRAFT')}
            disabled={isSubmitting}
          >
            <Save className="h-4 w-4 mr-2" />
            保存草稿
          </Button>
          <Button
            onClick={() => handleSave('PUBLISHED')}
            disabled={isSubmitting}
          >
            {isSubmitting ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                保存中...
              </>
            ) : (
              <>
                <Save className="h-4 w-4 mr-2" />
                发布文章
              </>
            )}
          </Button>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* 左侧：编辑表单 */}
        <div className={`space-y-6 ${isPreview ? 'lg:col-span-1' : 'lg:col-span-2'}`}>
          {/* 基本信息 */}
          <Card>
            <CardHeader>
              <CardTitle>基本信息</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="title">文章标题 *</Label>
                <Input
                  id="title"
                  value={formData.title}
                  onChange={(e) => handleInputChange('title', e.target.value)}
                  placeholder="请输入文章标题"
                  className="mt-1"
                />
              </div>
              
              <div>
                <Label htmlFor="description">文章描述</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  placeholder="请输入文章描述（可选）"
                  rows={3}
                  className="mt-1"
                />
              </div>

              <div>
                <Label htmlFor="content">文章内容 *</Label>
                <Textarea
                  id="content"
                  value={formData.content}
                  onChange={(e) => handleInputChange('content', e.target.value)}
                  placeholder="请输入文章内容，支持 Markdown 格式"
                  rows={15}
                  className="mt-1 font-mono"
                />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 右侧：设置面板 */}
        <div className="space-y-6">
          {/* 分类设置 */}
          <Card>
            <CardHeader>
              <CardTitle>分类设置</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <Label>选择分类</Label>
                <select
                  value={formData.categoryId}
                  onChange={(e) => handleInputChange('categoryId', e.target.value)}
                  className="w-full px-3 py-2 border border-input rounded-md bg-background text-sm"
                >
                  <option value="">无分类</option>
                  {categories.map(category => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
              </div>
            </CardContent>
          </Card>

          {/* 标签设置 */}
          <Card>
            <CardHeader>
              <CardTitle>标签设置</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                <Label>选择标签</Label>
                <div className="flex flex-wrap gap-2">
                  {tags.map(tag => (
                    <Badge
                      key={tag.id}
                      variant={formData.tagIds.includes(tag.id) ? 'default' : 'outline'}
                      className="cursor-pointer hover:bg-primary/80"
                      onClick={() => handleTagToggle(tag.id)}
                    >
                      {tag.name}
                    </Badge>
                  ))}
                </div>
                {tags.length === 0 && (
                  <p className="text-sm text-muted-foreground">暂无标签</p>
                )}
              </div>
            </CardContent>
          </Card>

          {/* 发布设置 */}
          <Card>
            <CardHeader>
              <CardTitle>发布设置</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="featured"
                    checked={formData.featured}
                    onChange={(e) => handleInputChange('featured', e.target.checked)}
                    className="rounded border-gray-300"
                  />
                  <Label htmlFor="featured">设为推荐文章</Label>
                </div>
                
                <div className="space-y-2">
                  <Label>当前状态</Label>
                  <div className="flex space-x-2">
                    <Badge variant={formData.status === 'DRAFT' ? 'secondary' : 'default'}>
                      {formData.status === 'DRAFT' ? '草稿' : '已发布'}
                    </Badge>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 预览面板 */}
        {isPreview && (
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle>文章预览</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="prose max-w-none">
                  <h1>{formData.title || '文章标题'}</h1>
                  {formData.description && (
                    <p className="text-lg text-muted-foreground">{formData.description}</p>
                  )}
                  <div className="mt-6">
                    {formData.content ? (
                      <div className="whitespace-pre-wrap">{formData.content}</div>
                    ) : (
                      <p className="text-muted-foreground">请输入文章内容以查看预览</p>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        )}
      </div>
    </div>
  )
}
